const api = require('./utils/api');
const {
  request
} = require('./utils/request.js');
const QQMapWX = require('./libs/qqmap-wx-jssdk');
App({
  globalData: {
    // https://v1.miaotongchefu.cn/v1 http://127.0.0.1:5000 https://jfxx.2028ka.cn/v1
    serverUrl: 'https://v1.miaotongchefu.cn/v1',
    service_icon: '',
    service_gzh_icon: 'hierarchy',
    userInfo: null,
    user_id: null,
    searchHistory: [],
    token: null,
    hasLogin: false,
    userLoginReadyCallback: null,
    platform: 'ios',
    pixelRatio: 2,
    statusBarHeight: 20,
    navHeight: 64,
    navTitleTop: 26,
    winHeight: 655,
    winWidth: 750,
    screenWidth: 375,
    screenHeight: 812,
    site_name: '',
    qqmapsdk: null,
    operation: null,
    isPay: false,


    loginCompleteCallbacks: [], // 等待登录完成的回调
    isLoginCompleted: false // 登录是否完成的标志

  },
  // 通知登录完成
  triggerLoginComplete() {
    this.globalData.isLoginCompleted = true;

    // 执行所有等待的回调
    this.globalData.loginCompleteCallbacks.forEach(callback => {
      try {
        callback();
      } catch (error) {
        console.error('登录完成回调执行失败:', error);
      }
    });

    // 清空回调数组
    this.globalData.loginCompleteCallbacks = [];
  },

  // 等待登录完成的方法
  waitForLogin(callback) {
    if (this.globalData.isLoginCompleted) {
      // 如果已经登录完成，立即执行
      callback();
    } else {
      // 否则加入等待队列
      this.globalData.loginCompleteCallbacks.push(callback);
    }
  },
  onLaunch: function (options) {
    try {
      let inviterId = null;
      if (options.query.scene) {
        const sceneStr = decodeURIComponent(options.query.scene);
        const parseScene = (str) => {
          const obj = {};
          const pairs = str.split('&');
          pairs.forEach(pair => {
            const [key, val] = pair.split('=');
            if (key) {
              obj[decodeURIComponent(key)] = decodeURIComponent(val || '');
            }
          });
          return obj;
        };

        const params = parseScene(sceneStr);
        console.log(params);
        const sharerIdStr = params.sharerId;

        if (sharerIdStr && !isNaN(sharerIdStr)) {
          inviterId = Number(sharerIdStr);
        }
      }

      if (!inviterId && options.query?.sharerId) {
        inviterId = Number(options.query.sharerId);
      }

      if (inviterId) {
        wx.setStorageSync('inviterId', inviterId);
        console.log('存储分享者ID:', inviterId);
      }
    } catch (error) {
      console.log("处理分享者失败", error);
    }
    this.checkForUpdate()
    wx.checkSession({
      success: () => {
        // 登录态有效，直接使用
        this.userLogin();
      },
      fail: () => {
        // 登录态已过期，重新登录
        this.userLogin();
      }
    });
    try {
      const res = wx.getSystemInfoSync()
      if (res.platform == 'ios') {
        this.globalData.platform = 'ios'
      } else if (res.platform == 'android') {
        this.globalData.platform = 'android'
      }
      // 导航高度
      let navHeight = res.statusBarHeight
      // 屏幕宽度/高度，单位px
      this.globalData.screenWidth = res.screenWidth
      this.globalData.screenHeight = res.screenHeight
      // 状态栏的高度，单位px
      this.globalData.statusBarHeight = res.statusBarHeight
      // 设备像素比
      this.globalData.pixelRatio = res.pixelRatio
      // 可使用窗口宽度，单位px
      this.globalData.winWidth = res.windowWidth
      // 安卓时，胶囊距离状态栏8px，iOS距离4px
      if (res.system && res.system.indexOf('Android') !== -1) {
        this.globalData.navHeight = navHeight + 14 + 32
        this.globalData.navTitleTop = navHeight + 8
        // 视窗高度 顶部有占位栏时
        this.globalData.winHeight = res.screenHeight - navHeight - 14 - 32
        // tab主页视窗高度
        this.globalData.winHeightTab = res.windowHeight - navHeight - 14 - 32
      } else {
        this.globalData.navHeight = navHeight + 12 + 32
        this.globalData.navTitleTop = navHeight + 4
        // 视窗高度 顶部有占位栏时
        this.globalData.winHeight = res.screenHeight - navHeight - 12 - 32
        // tab主页视窗高度
        this.globalData.winHeightTab = res.windowHeight - navHeight - 12 - 32
      }
    } catch (e) {
      console.error(e)
    }

  },
  userLogin: function () {
    wx.showLoading({
      title: '登录中...',
    });
    wx.login({
      success: res => {
        if (res.code) {
          // 向服务器发送code
          wx.request({
            url: this.globalData.serverUrl + api.login,
            method: 'POST',
            data: {
              code: res.code,
              app_id: 'wx1830687798261185'
            },
            success: loginRes => {
              wx.hideLoading();

              if (loginRes.statusCode === 200 && loginRes.data.code === 1) {
                // 登录成功
                const userInfo = loginRes.data.data.userInfo || loginRes.data.userInfo;
                const token = loginRes.data.data.token || '';
                this.globalData.userInfo = userInfo;
                this.globalData.hasLogin = true;
                this.globalData.user_id = userInfo.user_id;
                this.globalData.token = token; // 确保token保存到全局


                const inviterId = wx.getStorageSync('inviterId')
                if (inviterId) {
                  this.bindShare(userInfo.user_id, inviterId);
                }
                wx.setStorageSync('tenant_id', userInfo.tenant_id)
                // 保存到存储
                wx.setStorageSync('userId', userInfo.user_id);
                wx.setStorageSync('token', token);
                wx.setStorageSync('userInfo', userInfo);


                // ✅ 登录成功后立即执行需要token的操作
                this.initPublicImage()
                this.initqqmap()
                this.initOperation()
                this.initIsPay()

                // ✅ 通知所有等待的页面
                this.triggerLoginComplete();

                // 如果已经存在回调，立即执行回调
                if (this.globalData.userLoginReadyCallback) {
                  this.globalData.userLoginReadyCallback(userInfo);
                }
              } else {
                // 登录失败
                this.showLoginError(loginRes.data.msg || '登录失败，请稍后重试');
              }
            },
            fail: err => {
              wx.hideLoading();
              this.showLoginError('网络错误，请检查网络连接');
              console.error('登录请求失败:', err);
            }
          });
        } else {
          wx.hideLoading();
          this.showLoginError('获取授权码失败');
          console.log('获取code失败', res.errMsg);
        }
      },
      fail: err => {
        wx.hideLoading();
        this.showLoginError('微信登录失败');
        console.error('wx.login调用失败:', err);
      }
    });
  },

  initPublicImage() {
    this.getConfig('gzh_img', res => {
      if (res.is_public) {
        this.globalData.service_gzh_icon = res.value
      }
    })
    this.getConfig('service_img', res => {
      if (res.is_public) {
        this.globalData.service_icon = res.value
      }
    })
  },
  initqqmap() {
    return new Promise((resolve, reject) => {
      if (this.globalData.qqmapsdk) {
        // 如果已经初始化过了，直接返回
        return resolve(this.globalData.qqmapsdk);
      }

      this.getConfig('qqmapsdk', res => {
        if (res && res.is_public && res.value) {
          this.globalData.qqmapsdk = new QQMapWX({
            key: res.value
          });
          resolve(this.globalData.qqmapsdk);
        } else {
          reject('qqmapsdk 配置不可用');
        }
      });
    });
  },
  initOperation() {
    this.getConfig('operation', res => {
      if (res && res.is_public && res.value) {
        this.globalData.operation = res.value
      }
    });
  },
  initIsPay() {
    this.getConfig('is_pay', res => {
      const isPay = res && res.is_public && res.value === true;
      this.globalData.isPay = isPay;
    });
  },

  showLoginError: function (message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  },

  checkLoginStatus: function () {
    return this.globalData.hasLogin;
  },

  saveSearchHistory: function (keyword) {
    let history = this.globalData.searchHistory;
    history = history.filter(item => item !== keyword);
    history.unshift(keyword);
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    this.globalData.searchHistory = history;
    wx.setStorageSync('searchHistory', history);
  },

  clearSearchHistory: function () {
    this.globalData.searchHistory = [];
    wx.removeStorageSync('searchHistory');
  },

  // 获取用户个人信息的公用方法
  getUserProfile: function (callback) {
    wx.request({
      url: this.globalData.serverUrl + api.userInfo,
      method: 'GET',
      data: {
        user_id: this.globalData.user_id
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')

      },
      success: res => {
        if (res.statusCode === 200 && res.data.code === 1) {
          // 获取成功
          callback && callback(res.data.data);
        } else {
          // 获取失败
          wx.showToast({
            title: res.data.msg || '获取用户信息失败',
            icon: 'none',
            duration: 2000
          });
          callback && callback(null);
        }
      },
      fail: err => {
        console.error('获取用户信息失败:', err);
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none',
          duration: 2000
        });
        callback && callback(null);
      }
    });
  },

  // 文件上传公用方法
  uploadFile: function (filePath, formData, callback) {
    try {
      if (!filePath) {
        wx.showToast({
          title: '文件路径不能为空',
          icon: 'none',
          duration: 2000
        });
        callback && callback(null);
        return;
      }
      formData = {
        user_id: this.globalData.userInfo.user_id
      }
      wx.uploadFile({
        url: this.globalData.serverUrl + '/upload',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        formData: formData || {},
        success: res => {
          try {
            const data = JSON.parse(res.data);
            if (res.statusCode === 200 && data.code === 1) {
              // 上传成功
              callback && callback(data);
            } else {
              // 上传失败
              wx.showToast({
                title: data.msg || '文件上传失败',
                icon: 'none',
                duration: 2000
              });
              callback && callback(null);
            }
          } catch (error) {
            console.error('解析响应失败:', error, res.data);
            wx.showToast({
              title: '服务器响应解析失败',
              icon: 'none',
              duration: 2000
            });
            callback && callback(null);
          }
        },
        fail: err => {
          console.error('文件上传失败:', err);
          wx.showToast({
            title: '网络错误，请检查网络连接',
            icon: 'none',
            duration: 2000
          });
          callback && callback(null);
        }
      });
    } catch (error) {
      callback && callback(null);
    }
  },
  // 文件上传公用方法
  uploadFileAi: function (filePath, formData, callback) {
    try {
      if (!filePath) {
        wx.showToast({
          title: '文件路径不能为空',
          icon: 'none',
          duration: 2000
        });
        callback && callback(null);
        return;
      }
      formData = {
        user_id: this.globalData.userInfo.user_id
      }
      wx.uploadFile({
        url: this.globalData.serverUrl + '/uploadAi',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        formData: formData || {},
        success: res => {
          try {
            const data = JSON.parse(res.data);
            if (res.statusCode === 200 && data.code === 1) {
              // 上传成功
              callback && callback(data);
            } else {
              // 上传失败
              wx.showToast({
                title: data.msg || '文件上传失败',
                icon: 'none',
                duration: 2000
              });
              callback && callback(null);
            }
          } catch (error) {
            console.error('解析响应失败:', error, res.data);
            wx.showToast({
              title: '服务器响应解析失败',
              icon: 'none',
              duration: 2000
            });
            callback && callback(null);
          }
        },
        fail: err => {
          console.error('文件上传失败:', err);
          wx.showToast({
            title: '网络错误，请检查网络连接',
            icon: 'none',
            duration: 2000
          });
          callback && callback(null);
        }
      });
    } catch (error) {
      callback && callback(null);
    }
  },
  // 更新TabBar选中状态的公共方法
  updateTabBarSelected: function (index) {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: index
      });
    }
  },

  getConfig(key, callback) {
    wx.request({
      url: this.globalData.serverUrl + '/api/admin/configs/mp/get/' + key,
      method: 'GET',
      data: {},
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: res => {
        const resData = res.data
        if (resData.code === 0) {
          callback && callback(resData.data);
        }
      },
      fail: err => {
        console.error('获取用户信息失败:', err);
        wx.showToast({
          title: '网络错误，请检查网络连接',
          icon: 'none',
          duration: 2000
        });
        callback && callback(null);
      }
    });
  },
  bindShare(userId, sharerId) {
    if (!sharerId || !userId || userId === sharerId) {
      console.log('参数不合法，跳过绑定');
      return;
    }
    request(api.shareBind, 'POST', {
        userId: userId,
        sharerId: sharerId
      })
      .then(res => {
        console.log('绑定成功：', res.data.msg);
      })
      .catch(err => {
        console.log('绑定失败：', err);
      });
  },
  /**
   * 检查小程序版本更新
   */
  checkForUpdate: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();

      // 检测是否有新版本
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          console.log('小程序有新版本可用');

          // 新版本下载完成
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已准备好，是否重启应用？',
              confirmText: '立即更新',
              confirmColor: '#FF6600',
              success: function (res) {
                if (res.confirm) {
                  // 使用新版本
                  updateManager.applyUpdate();
                }
              }
            });
          });

          // 新版本下载失败
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              title: '更新失败',
              content: '新版本下载失败，请删除当前小程序，重新搜索打开',
              confirmColor: '#FF6600',
              showCancel: false
            });
          });
        }
      });
    } else {
      // 如果用户设备不支持自动更新
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级微信后重试',
        confirmColor: '#FF6600',
        showCancel: false
      });
    }
  },

  openShow(opt = {}) {
    const query = Object.keys(opt)
      .map(key => `${key}=${encodeURIComponent(opt[key])}`)
      .join('&');

    wx.navigateTo({
      url: `/pages/imgshow/index?${query}`,
    });
  },


  goPayPage() {
    const systemInfo = wx.getSystemInfoSync();
    const system = systemInfo.system.toLowerCase(); // 例子："ios 16.3.1" 或 
    this.openShow({
      url: this.globalData.service_gzh_icon,
      title: '在线充值'
    })
    return
    if (!this.globalData.isPay) {
      this.openShow({
        url: this.globalData.service_gzh_icon,
        title: '在线充值'
      })
      return
    }
    if (system.indexOf('ios') > -1) {
      this.openShow({
        url: this.globalData.service_gzh_icon,
        title: '在线充值'
      })
    } else if (system.indexOf('android') > -1) {
      wx.navigateTo({
        url: '/pages/buy-times/buy-times',
      })
    } else {
      wx.navigateTo({
        url: '/pages/buy-times/buy-times',
      })
    }
  },

})